package org.dromara.common.dynamicDs.init;

import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.creator.DataSourceProperty;
import com.baomidou.dynamic.datasource.creator.DefaultDataSourceCreator;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.constant.TenantConstants;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.dynamicDs.domain.SysDynamicDs;
import org.dromara.common.dynamicDs.service.ISysDynamicDsService;
import org.dromara.common.redis.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author: gxp
 * @desc: todo
 * @create: 2024-09-26 11:30
 **/
@Component
@Slf4j
public class DynamicDsInit implements CommandLineRunner {
    @Resource
    private ISysDynamicDsService sysDynamicDsService;
    @Autowired
    DataSource dataSource;
    @Autowired
    DefaultDataSourceCreator dataSourceCreator;
    private static final ConcurrentHashMap<String, String> concurrentHashMap = new ConcurrentHashMap<>();
    @Override
    public void run(String... args) throws Exception {
          List<SysDynamicDs> list = sysDynamicDsService.listAll();
          List<String> dsList=new ArrayList<>();
          list.forEach(item -> {
              if(!dsList.contains(item.getName())) {
                  DataSourceProperty result = new DataSourceProperty();
                  result.setPoolName(item.getName());
                  result.setDriverClassName(item.getDriverClassName());
                  result.setUrl(item.getUrl());
                  result.setUsername(item.getUsername());
                  result.setPassword(item.getPassword());
                  DynamicRoutingDataSource ds = (DynamicRoutingDataSource) dataSource;
                  ds.addDataSource(result.getPoolName(), dataSourceCreator.createDataSource(result));
                  log.info("添加数据源：{}", item.getName());
                  concurrentHashMap.put(item.getTenantId(), item.getName());
                  RedisUtils.setCacheObject(TenantConstants.CACHE_TENANT_ID +item.getTenantId(), item.getName());
              }
              dsList.add(item.getName());
          });
    }

    public static String getDsName(String tenantId) {
        String tenantDsName=concurrentHashMap.get(tenantId);
        if(StringUtils.isEmpty(tenantDsName)){
            return RedisUtils.getCacheObject(TenantConstants.CACHE_TENANT_ID +tenantId);
        }else{
            return tenantDsName;
        }
    }
}
